﻿using System;
using uForum.Businesslogic;
using uForum.Configuration;
using umbraco.cms.businesslogic;
using umbraco.cms.businesslogic.web;
using umbDeleteEventArgs=umbraco.cms.businesslogic.DeleteEventArgs;

namespace uForum
{

	public class NewForumHandler : umbraco.BusinessLogic.ApplicationBase
	{

		public NewForumHandler()
		{
			Document.AfterPublish += Document_AfterPublish;
			Document.AfterDelete += Document_AfterDelete;
		}

		void Document_AfterDelete(Document sender, umbDeleteEventArgs e)
		{
			if (sender.ContentType.Alias.Equals(ContentProperties.ForumDocumentTypeAlias, StringComparison.InvariantCultureIgnoreCase))
			{

				umbraco.BusinessLogic.Log.Add(umbraco.BusinessLogic.LogTypes.Debug, 0, "forum has been deleted");

				var f = new Forum(sender.Id);

				umbraco.BusinessLogic.Log.Add(umbraco.BusinessLogic.LogTypes.Debug, f.Id, f.Title);

				f.Delete();

			}
		}

		void Document_AfterPublish(Document sender, PublishEventArgs e)
		{

			if (sender.ContentType.Alias.Equals(ContentProperties.ForumDocumentTypeAlias, StringComparison.InvariantCultureIgnoreCase))
			{
			    var f = new Forum(sender.Id);
			    if (f.Exists)
			    {
			        f.Save();
			    }
			    else
			    {
			        int parentId = sender.Level == 1 ? -1 : sender.Parent.Id;
			        Forum.Create(sender.Id, parentId, sender.sortOrder);
			    }
			}
		}
	}
}
